package com.jeesite.modules.kj.api.filter;

import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.common.interfaces.CurrentUser;
import com.jeesite.modules.kj.api.enumCode.UnicomResponseEnums;
import com.jeesite.modules.kj.api.exception.UnicomRuntimeException;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(String.class)
                && parameter.hasParameterAnnotation(CurrentUser.class);
    }
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        //TODO  获取当前用户
        String memberId = (String)webRequest.getAttribute("memberId", RequestAttributes.SCOPE_REQUEST);
        if (StringUtils.isNotBlank(memberId)) {
            return memberId;
        }

        throw new UnicomRuntimeException(UnicomResponseEnums.MUST_LOGIN);
    }
}
